import random
import re
import sqlite3
from datetime import datetime

import requests
from booktest import requests
import urllib.request
from django.http import HttpResponse, JsonResponse
from django.shortcuts import render,get_object_or_404
from lxml import etree

from .models import Category, Anime, Label, Status
from django.conf import settings
from django.core.paginator import Paginator, Page


# Create your views here.
def index(request):
    """
        新建视图函数
        :param request: 用于处理请求信息
        :return: 返回响应字符串
        """
    cs = Category.objects.all()
    ans = Anime.objects.all()
    ans_date = Anime.objects.all().order_by('-pub_date')

    today_weekday = datetime.now().weekday()
    same_weekday_animes = Anime.objects.filter(
        pub_date__week_day=today_weekday + 1
    )
    return render(request, "main/index.html", context={"cs": cs, "ans": ans, "ans_date": ans_date, "same_weekday_animes": same_weekday_animes, })


def detail(request, num):
    ans = Anime.objects.get(id=num)
    episode_count = ans.episode

    episodes = []
    for i in range(1, episode_count + 1):
        animes = {
            "id": ans.id,
            "episode": i,
            "agelink": ans.agelink,
        }
        episodes.append(animes)

    # 提取标签名称
    labels = [label.title for label in ans.label.all()]

    # 获取与该动漫具有相同标签的所有动漫（不包括当前动漫）
    same_label_anime = Anime.objects.filter(
        label__in=ans.label.all()
    ).exclude(id=ans.id)

    random_same_anime = same_label_anime.order_by('?')[:6]

    context = {"ans": ans,
               "ansid": ans.id,
               "episodes": episodes,
               "labels": labels,
               "random_same_anime": random_same_anime,
               }

    return render(request, "main/detail.html", context)


def recommend(request):
    today_weekday = datetime.now().weekday()
    same_weekday_animes = Anime.objects.filter(
        pub_date__week_day=today_weekday + 1
    )
    paginator = Paginator(same_weekday_animes, 18)
    page_num = request.GET.get("page", 1)
    page = paginator.get_page(page_num)

    return render(request, "main/recommend.html", context={"same_weekday_animes": len(same_weekday_animes), "page": page, "page_num": page_num, })


def catalog(request):
    labels = Label.objects.all()
    status = Status.objects.all()
    category = Category.objects.all()
    anime = Anime.objects.all()

    paginator = Paginator(anime, 20)
    page_num = request.GET.get("page", 1)
    page = paginator.get_page(page_num)
    context = {
        "labels": labels,
        "status": status,
        "category": category,
        "anime_len": len(anime),
        "page": page,
        "page_num": page_num,
    }
    return render(request, "main/catalog.html", context)


def category(request, c_id):
    c = get_object_or_404(Category, id=c_id)


    labels = Label.objects.all()
    status = Status.objects.all()
    category = Category.objects.all()
    anime = c.anime_set.all()

    paginator = Paginator(anime, 20)
    page_num = request.GET.get("page", 1)
    page = paginator.get_page(page_num)
    context = {
        "labels": labels,
        "status": status,
        "category": category,
        "anime_len": len(anime),
        "page": page,
        "page_num": page_num,
    }
    return render(request, "main/catalog.html", context)


def label(request, l_id):
    l = get_object_or_404(Label, id=l_id)

    labels = Label.objects.all()
    status = Status.objects.all()
    category = Category.objects.all()
    anime = Anime.objects.filter(label=l)

    paginator = Paginator(anime, 20)
    page_num = request.GET.get("page", 1)
    page = paginator.get_page(page_num)
    context = {
        "labels": labels,
        "status": status,
        "category": category,
        "anime_len": len(anime),
        "page": page,
        "page_num": page_num,
    }
    return render(request, "main/catalog.html", context)


def status(request, s_id):
    s = get_object_or_404(Status, id=s_id)

    labels = Label.objects.all()
    status = Status.objects.all()
    category = Category.objects.all()
    anime = Anime.objects.filter(status=s)

    paginator = Paginator(anime, 20)
    page_num = request.GET.get("page", 1)
    page = paginator.get_page(page_num)
    context = {
        "labels": labels,
        "status": status,
        "category": category,
        "anime_len": len(anime),
        "page": page,
        "page_num": page_num,
    }
    return render(request, "main/catalog.html", context)


def rank(request):
    s = get_object_or_404(Status, id=2)
    ans_views = Anime.objects.filter(status=s)

    modified_views = []
    for anime in ans_views:
        # 去掉最后的 'w'，并转换为整数
        number = float(anime.views[:-1])  # 假设剩下的部分是有效的数字
        anime_view = {
            "id": anime.id,
            "title": anime.title,
            "views": number,
            "imglink": anime.imglink,
        }
        modified_views.append(anime_view)
    modified_views.sort(key=lambda x: x['views'], reverse=True)
    modified_views = modified_views[:50]

    return render(request, "main/rank.html", context={"modified_views": modified_views, })


def play(agelink, i):
    url = f"https://www.agedm.org/play/{agelink}/1/{i}"

    # url = "https://www.agedm.org/play/20110012/1/1"
    headers = {
        "user-agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/129.0.0.0 Safari/537.36",
    }
    req = urllib.request.Request(url, headers=headers)
    response = urllib.request.urlopen(req)
    content = response.read().decode()

    web = re.findall(r'<iframe id="iframeForVideo" src="(.*?)" allowfullscreen="allowfullscreen" mozallowfullscreen="mozallowfullscreen" msallowfullscreen="msallowfullscreen" oallowfullscreen="oallowfullscreen" webkitallowfullscreen="webkitallowfullscreen"></iframe>', content)
    return web[0]


def get_video_link(request):
    if request.method == "GET":
        agelink = request.GET.get('agelink')
        episode_number = request.GET.get('episode')

        # 调用爬虫函数获取视频链接
        video_link = play(agelink, episode_number)

        return JsonResponse({'video_link': video_link})